 package com.eims.sls_app.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import bls.juejin.cn.R;
import com.eims.sls_app.dataaccess.Schemes;
import com.eims.sls_app.dataaccess.utils.HttpUtils;
import com.eims.sls_app.protocol.MD5;
import com.eims.sls_app.protocol.RspBodyBaseBean;
import com.eims.sls_app.ui.adapter.CenterLotteryAdapter;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.LotteryUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/***
 * 所有追号的投注信息
 * 
 * @author Administrator
 * 
 */
public class FollowBetLottery implements OnScrollListener {
	private View view;
	private ListView listView;
	private CenterLotteryAdapter adapter;
	private Context context;
	private TextView tv_title;

	private MyHandler myHandler;
	private MyAsynTask myAsynTask;

	private List<List<Schemes>> listAllSchemes = new ArrayList<List<Schemes>>();
	private List<String> list = new ArrayList<String>();

	private String opt, auth, info, time, imei, crc, key; // 格式化后的参数

	private int size = 20;
	private int pageIndex = 1; // 页码
	private int pageSize = size; // 每页显示行数

	/** 要更改的 **/
	private LinearLayout ll;
	private ProgressBar pb;
	private int isEnd = 0;

	// 最后可见条目的索引
	private int lastVisibleIndex;

	public FollowBetLottery(Context context, View v) {
		this.view = v;
		this.context = context;
		myHandler = new MyHandler();
		time = RspBodyBaseBean.getTime();
		imei = RspBodyBaseBean.getIMEI(context);
		// key = MD5.md5(App.user.getUserPass() + App.MD5_key);
		key = App.key;
	}

	public void init() {
		listView = (ListView) view.findViewById(R.id.ll_all_listView);
		tv_title = (TextView) view.findViewById(R.id.tv_title);
		tv_title.setText("追号订单");

		listView.setOnScrollListener(FollowBetLottery.this);

		/** 要更改的 新加的加载图片 **/
		ll = new LinearLayout(context);
		pb = new ProgressBar(context);
		ll.setGravity(Gravity.CENTER);
		ll.addView(pb);
		/** 要加在 setAdapter之前 **/
		listView.addFooterView(ll);

		adapter = new CenterLotteryAdapter(context, list, listAllSchemes,
				new MyItemCLickListener());
		listView.setAdapter(adapter);

		myAsynTask = new MyAsynTask();
		myAsynTask.execute();
	}

	private List<Schemes> listDetail;

	/** 异步任务 */
	class MyAsynTask extends AsyncTask<Void, Integer, String> {
		/** 在后台执行的程序 */
		@Override
		protected String doInBackground(Void... params) {
			boolean falg;

			info = "{\"lotteryId\":\"" + App.lotteryIds + ",72,73"
					+ "\", \"pageIndex\":\"" + pageIndex + "\",\"pageSize\":\""
					+ pageSize + "\"," + "\"sort\":\"" + 0
					+ "\", \"sortType\":\"0\"}";

			Log.i("x", "获得 追号 投注记录    info  " + info);

			opt = "50";
			crc = RspBodyBaseBean.getCrc(time, imei, key, info,
					App.user.getUid());

			auth = RspBodyBaseBean.getAuth(crc, time, imei,
					App.user.getUid());
			String[] values = { opt, auth, info };
			String result = HttpUtils.doPost(App.names, values,
					App.path);

			Log.e("追号", result);

			// System.out.println("所有追号内容----  " + result);

			if ("-500".equals(result))
				return result;

			if (null == result)
				return "1";

			try {
				JSONObject item = new JSONObject(result);
				if ("0".equals(item.optString("error"))) {
					JSONArray array = new JSONArray(
							item.optString("chaseTaskDetailsList"));
					// List<Schemes> listDetail = null;
					for (int i = 0; i < array.length(); i++) {
						JSONObject object = array.getJSONObject(i);
						JSONArray array2 = new JSONArray(
								object.getString("chaseTaskDetail"));

						if (!list.contains(object.getString("date"))) {

							falg = false;

							list.add(object.getString("date"));

							listDetail = new ArrayList<Schemes>();
						}

						else
							falg = true;
						Schemes scheme;
						for (int j = 0; j < array2.length(); j++) {
							JSONObject items = array2.getJSONObject(j);
							scheme = new Schemes();
							scheme.setId(items.optString("id"));
							scheme.setChaseTaskID(items.optInt("id"));
							scheme.setInitiateUserID("userID");
							scheme.setDateTime(items.optString("chaseDateTime"));
							scheme.setLotteryID(items.optString("lotteryID"));
							scheme.setQuashStatus(items.optInt("quashStatus"));
							scheme.setLotteryNumber(items
									.optString("lotteryNumber"));
							// 454
							scheme.setDetailMoney(items
									.optDouble("detailMoney"));

							scheme.setHandselMoney(items
									.optDouble("handselMoney"));

							scheme.setMoney(items.getDouble("sumChaseMoney"));
							scheme.setSumSchemeMoney(items
									.getDouble("sumSchemeMoney"));
							scheme.setWinMoneyNoWithTax(items
									.optDouble("winMoneyNoWithTax"));
							scheme.setStopWhenWinMoney(items
									.optDouble("stopWhenWinMoney"));
							scheme.setLotteryName(items
									.optString("lotteryName"));
							scheme.setInitiateName(items.optString("userName"));
							scheme.setSchemeIsOpened(items
									.optString("isOpened"));
							scheme.setSumChaseCount(items
									.optInt("sumChaseCount"));
							scheme.setIsPurchasing("True");
							scheme.setWinDescription(items
									.optString("WinDescription"));
							scheme.setIsChase(1);
							scheme.setSchemeStatus(items
									.optString("schemeStatus"));
							listDetail.add(scheme);
						}
						if (!falg)
							listAllSchemes.add(listDetail);
					}

				} else {
					return item.optString("error");
				}
			} catch (Exception e) {
				Log.i("x", "错误信息     " + e.getMessage());
				return "-100";
			}

			return "0";
		}

		@Override
		protected void onPostExecute(String result) {
			if (null == result)
				return;
			myHandler.sendEmptyMessage(Integer.parseInt(result));
			super.onPostExecute(result);
		}
	}

	/** 进行页面刷新 */
	@SuppressLint("HandlerLeak")
	class MyHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				getThreeMonth();
				adapter.setDate(list, listAllSchemes);
				adapter.notifyDataSetChanged();
				listView.setOnScrollListener(FollowBetLottery.this);
				if (getTotalCount() < 20)
					myHandler.sendEmptyMessage(-1);

				if (!LotteryUtils.checkThreeMonth(list)) {
					myHandler.sendEmptyMessage(-1);
				}
				
				
				
				break;
			// case -1:
			// listView.removeFooterView(ll);
			// listView.setOnScrollListener(null);
			// break;
			default:
				listView.removeFooterView(ll);
				listView.setOnScrollListener(null);
				break;
			}
			super.handleMessage(msg);
		}
	}

	private void getThreeMonth() {
		String now = LotteryUtils.getSchemeTime(System.currentTimeMillis());
		for (int i = 0; i < list.size(); i++) {
			if (!LotteryUtils.compareMonth(now, list.get(i))) {
				list.remove(i);
				listAllSchemes.remove(i);
			}
		}
	}

	private int getTotalCount() {
		int total = 0;
		for (List<Schemes> list : listAllSchemes) {
			total += list.size();
		}
		return total;
	}

	class MyItemCLickListener implements OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> arg0, View view, int position,
				long arg3) {
			TextView tv_id = (TextView) view.findViewById(R.id.tv_id);
			int itemId = Integer.parseInt(tv_id.getText().toString());

			Schemes scheme = listAllSchemes.get(itemId).get(position);
			Intent intent = new Intent(context, MyFollowLotteryInfo.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			App.scheme=scheme;
			intent.putExtra("scheme", scheme);
			context.startActivity(intent);
		}
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {

		lastVisibleIndex = firstVisibleItem + visibleItemCount - 1;

	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {

		if (scrollState == OnScrollListener.SCROLL_STATE_IDLE
				&& lastVisibleIndex == adapter.getCount()) {
			if (isEnd != getTotalCount()) {
				pageIndex++;
				isEnd = getTotalCount();
				myAsynTask = new MyAsynTask();
				myAsynTask.execute();
			} else {
				myHandler.sendEmptyMessage(-1);
			}
		}
	}

}
